<template>
  <div style="overflow: auto; height: 100%">
    <div class="loading" v-if="loading">
      <a-spin :spinning="loading" />
    </div>
    <!-- defaultExpandAll -->

    <a-directory-tree
      v-else
      class="tree"
      :selectedKeys="selected"
      :blockNode="true"
      :show-line="{ showLeafIcon: false }"
      :tree-data="treeData"
      :fieldNames="{ key: 'categoryId', title: 'categoryName' }"
      :showIcon="false"
    >
      <template #switcherIcon="{ switcherCls }">
        <down-outlined :class="switcherCls" />
      </template>
      <template #title="item">
        <div
          class="title"
          :class="{
            active:
              selected.includes(item.categoryId) &&
              (item?.children || [])?.length === 0,
          }"
          @click="onClick(item)"
        >
          {{ item.categoryName }}
        </div>
      </template>
    </a-directory-tree>
  </div>
</template>
<script setup>
import { useVModel } from '@vueuse/core'
import { DownOutlined } from '@ant-design/icons-vue'
import { getCategoryTree } from '@/api/db.js'
import { onMounted, ref } from 'vue'
import { useDbType } from './provide-context.js'
/**
 * 外部参数
 */
let props = defineProps({
  selected: { type: Array, default: () => [] },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:selectedInfo', 'ready'])
/**
 * 双向绑定
 */
let selectedInfo = useVModel(props, 'selectedInfo', emit)
let treeData = ref([])
let selected = ref([])
/**
 * 选中详情
 */
function onClick(item) {
  if ((item?.children || [])?.length === 0) {
    selectedInfo.value = item
    selected.value = [item.categoryId]
  }
}
/**
 * 数据初始化
 */
let loading = ref(false)
let dbType = useDbType()
onMounted(async () => {
  loading.value = true
  try {
    let result = await getCategoryTree({}, dbType)
    treeData.value = result.data || []
    emit('ready', treeData.value)
  } catch (e) {
    console.log(e)
  }
  loading.value = false
})
</script>
<style lang="less" scoped>
// .ant-tree {
//   background-color: red;
//   .ant-tree-switcher-noop {
//     display: none;
//   }
//   .ant-tree-node-selected {
//     color: #0086ff;
//     background-color: #fff;
//   }
// }
.tree {
  .title {
    position: relative;
    color: #000;
    &.active {
      color: #3d6d99;
      &::after {
        content: ' ';
        position: absolute;
        right: -36px;
        width: 0;
        height: 0;
        border-right: 12px solid #fff;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        pointer-events: none;
      }
    }
  }
}
:deep(.ant-tree.ant-tree-directory .ant-tree-treenode-selected:hover::before),
:deep(.ant-tree.ant-tree-directory .ant-tree-treenode-selected::before) {
  background-color: white;
}

:deep(.ant-tree.ant-tree-directory)
  .ant-tree-treenode-selected
  .ant-tree-switcher {
  color: #000;
}
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
